import axios from "axios";
import qs from "qs";
import userUtil from "./userUtil";
import Vue from "vue";
import api from "../config/api";
// import { showFullScreenLoading, tryHideFullScreenLoading } from "./serviceHelp";
//本地
// axios.defaults.baseURL = "http://192.168.0.120:8080/api/";
//测试库
//
axios.defaults.baseURL = "https://www.go4nines.com/easton_interface/api/"; // 正式库
// axios.defaults.baseURL = "http://118.190.107.197:6151/api/"; // 测试库

// 创建一个拥有通用配置的axios实例
const http = axios.create({
  baseURL: axios.defaults.baseURL, // api 的 base_url
  transformResponse: [data => JSON.parse(data)], // 对 data 进行任意转换处理
  timeout: 50000, // 请求超时
  // 定义可获得的http响应状态码
  // return true、设置为null或者undefined，promise将resolved,否则将rejected
  validateStatus(status) {
    return status >= 200 && status < 500;
  }
});

// 返回结果处理
http.interceptors.response.use();

// http instance
export default http;
export async function post(url, data, params) {
  console.log(qs.stringify(data));
  return http({
    method: "post",
    url,
    data: qs.stringify(data),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    params: params,
    showLoading: true
  });
}

export async function sendPost(url, data, show) {
  // 请求数据
  // if (show) {
  //   tryHideFullScreenLoading();
  // } else {
  //   showFullScreenLoading(); // 显示加载效果
  // }
  return new Promise((resolve, reject) => {
    _getRequest(url, resolve, reject, data);
  });
}

function _getRequest(url, resolve, reject, data = {}) {
  let user = userUtil.get();
  let token = "";
  if (user != null && typeof user != undefined) {
    token = user.token;
  }
  var param = new Object(data);
  param.token = token;
  // console.log("请求参数:", param);
  axios({
    url: url,
    method: "post",
    data: qs.stringify(param),
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  })
    .then(res => {
      // 请求成功
      // tryHideFullScreenLoading(); // 隐藏加载效果
      // console.log("返回参数:", res.data);
      if (res.data.code == 0) {
        Vue.prototype.$msg.error(res.data.msg);
      } else if (res.data.code == 1) {
        if (res.data.success == 2) {
          Vue.prototype.$msg.error(res.data.msg);
          setTimeout(function(){  }, 3000);
          location.href = Vue.prototype.pageUrl + "login";
          return;
        }
        if (res.data.success == 3) {
          Vue.prototype.$msg.error(res.data.msg);
          setTimeout(function(){  }, 3000);
          location.href = Vue.prototype.pageUrl + "login";
          return;
        }
        if (res.data.success == 5) {
          Vue.prototype.$msg.error("登录失效，请联系管理人员");
          return;
        }
        if (res.data.success == 4) {


          Vue.prototype.$msg.error("该账号已在其他地方登录");
          location.href = Vue.prototype.pageUrl + "login";
          return;
        }
        resolve(res.data);
      }
    })
    .catch(() => {
      // 请求失败
      reject();
     // Vue.prototype.$msg.error("请求失败");
    });
}

export async function uploadFile(file, path) {
  let fd = new FormData();
  fd.append("file", file);
  return new Promise((resolve, reject) => {
    _uploadFile(api.updateFile + "?folder=" + path, resolve, reject, fd);
  });
}

function _uploadFile(url, resolve, reject, data) {
  axios({
    url: url,
    method: "post",
    data: data,
    header: {
      "Content-Type": "multipart/form-data"
    }
  })
    .then(res => {
      // console.log("返回参数:", res.data);
      if (res.data.success == true) {
        resolve(res.data);
      } else {
        Vue.prototype.$msg.error(res.data.msg);
        resolve(res.data);
      }
    })
    .catch(() => {
      reject();
     // Vue.prototype.$msg.error("请求失败");
    });
}

/**
 * @param {string} url
 * @param {object} params
 */
export async function get(url, params = {}) {
  return http({
    method: "get",
    url,
    params,
    showLoading: true
  });
}

export async function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = e => {
      resolve(e.target.result);
    };
    // readAsDataURL
    fileReader.readAsDataURL(blob);
    fileReader.onerror = () => {
      reject(new Error("blobToBase64 error"));
    };
  });
}
